package com.zhw.aop;

import com.alibaba.fastjson.JSONObject;
import com.zhw.Util.JwtUtils;
import com.zhw.mapper.LogMapper;
import com.zhw.mapper.UserMapper;
import com.zhw.pojo.entry.Log;
import com.zhw.pojo.entry.User;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;

    @Autowired
    LogMapper logMapper;


    @Autowired
    UserMapper userMapper;


    @Pointcut("execution(* com.zhw.service.*.*(..)) ")//扫描这个包下任意方法、任意参数类型的方法
    public void pc(){}



    @Around("pc()&&!@annotation(com.zhw.anno.Login)")
    public Object operationLogs(ProceedingJoinPoint jp) throws Throwable {

        String token = request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(token);
        //操作人员ID
        String id = (String) claims.get("id");
        User user = userMapper.getByID(Long.valueOf(id));



        //方法执行之前
        log.info("客户操作日志之前");

        //请求接口路径
        String uri = request.getRequestURI();

        //请求参数
        Object[] param = jp.getArgs();
        String string = Arrays.toString(param);

        long begin = System.currentTimeMillis();
        //执行原始方法
        Object result = jp.proceed();
        long end = System.currentTimeMillis();


        //响应码
        int code = response.getStatus();

        //操作结果
        String jsonString = JSONObject.toJSONString(result);



        //方法执行之后
        log.info("客户操作日志之后");

        //操作耗时
        long exeTime = end - begin;



        String detail=code==200?"操作成功":"操作失败";

        Log log=new Log(null,uri,code,detail,Arrays.toString(param),user.getUsername(),exeTime, LocalDateTime.now(),jsonString);

        logMapper.save(log);

        return result;
    }



}
